package com.caipos.mqtt.handler;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.caipos.mqtt.entity.MqttData;
import com.caipos.mqtt.entity.SensorDataDO;
import com.caipos.util.JsonUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.PathMatcher;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
@Slf4j
@RequiredArgsConstructor
public class CaiposMessageHandler implements MessageHandler{

    @Autowired
    private PathMatcher pathMatcher;
    @Autowired
    private SensorDataHandler fourGHandler;

//    @Autowired
//    private StringRedisTemplate stringRedisTemplate;

    @Value("${yanshi.gwid:190718B11}")
    private String gwid;

    private final Map<String, Integer> yuZhiDianMap = Map.of(
            "190718B11333100101", 1,//闸门
            "190718B11103101", 2,//水泵/喷灌溉
            "190718B11103100", 3//风机
    );
    public final static String ACCESS_TOKEN_KEY = "accessToken_J56830537";
    public final static String CAMERA_CODE = "J56830537";
    public final static String PETSET_URL = "https://open.ys7.com/api/lapp/device/preset/move";
    private RestTemplate restTemplate=new RestTemplate();
    /**
     * mqtt接收过来的数据流
     */
    @Override
    public void handleMessage(Message<?> message) throws MessagingException {
        String payload = message.getPayload().toString();
        String topic=message.getHeaders().get("mqtt_receivedTopic").toString();
        JSONObject jo = JsonUtil.getJsonObj(payload);
//        log.error(topic);
        if(jo==null)return;
        //收到mqtt网关上传过来的传感器数据
        if(pathMatcher.match("kebai/uc/?????????/report/sensor",topic)){
//            log.error(payload);
            MqttData mqttData=null;
            try{
                mqttData= jo.toJavaObject(MqttData.class);
            }catch (Exception e){
                log.error(e.getMessage());
                e.printStackTrace();
                return;
            }
            if("190718B11".equals(mqttData.getMqttData1Entity().getGwid())){
//                log.error(payload);
            }
            if("220905J01".equals(mqttData.getMqttData1Entity().getGwid())){
//                log.error(payload);
            }
            //数据解析：
            List<SensorDataDO> sensorDataLists = fourGHandler.analysis(mqttData);

//            //向所有订阅的楼下大屏群发websocket
//            if(gwid.equals(mqttData.getMqttData1Entity().getGwid())){
//                WebSocketMsg wsm=new WebSocketMsg();
//                wsm.setMsg(sensorDataLists);
//                wsm.setCode(100);
//                TextWebSocketFrame tws = new TextWebSocketFrame(JSON.toJSONString(wsm));
//                // websocket群发
//                ChannelSupervise.send2All(tws);
//            }

            if(sensorDataLists==null||sensorDataLists.isEmpty()||sensorDataLists.size()==0){
                return;
            }
            for(SensorDataDO sdd:sensorDataLists){
                //在此可以进行数据检查、存储等操作：
                fourGHandler.dataStore(sdd);
            }
        }

        //服务器下发的控制命令topic:
        if(pathMatcher.match("kebai/gw/?????????",topic)){
        }
        //网关发出的对服务器命令响应的topic:
        if(pathMatcher.match("kebai/uc/gw/**",topic)){
            String gwidRes=jo.getJSONObject("Data").getString("gwid");
            if(gwid==null){
                return;
            }
            //记录网关响应
            log.info("GW Response:"+payload);

            String [] gwidArr=gwid.split(",");
            boolean flag=false;
            for (int i = 0; i < gwidArr.length; i++) {
                if(gwidArr[i].equals(gwidRes)){
                    flag=true;
                    break;
                }
            }
            //向所有订阅者群发websocket
            if(flag){
                String ndid=jo.getJSONObject("Data").getString("ndid");
                String devidShort=jo.getJSONObject("Data").getString("devid").replace("[","")
                        .replace("]","").replace(",","")
                        .replaceAll("\"","");
                String deviceid=ndid+devidShort;

                String devicestatus=null;
                if(deviceid.length()==15){
                    devicestatus=jo.getJSONObject("Data").getBooleanValue("devst")==true?"true":"false";
                }
                if(deviceid.length()==18){
                    JSONArray ja = jo.getJSONObject("Data").getJSONArray("devst");
                    if(ja.getBoolean(0)==true&&ja.getBoolean(1)==false){
                        devicestatus="forward";
                    }
                    if(ja.getBoolean(0)==false&&ja.getBoolean(1)==true){
                        devicestatus="back";
                    }
                    if(ja.getBoolean(0)==false&&ja.getBoolean(1)==false){
                        devicestatus="stop";
                    }
                }
                Map<String,Object> map=new HashMap<>();
                map.put("deviceid",deviceid);
                map.put("devicestatus",devicestatus);
            }
        }

        //网关主动上传的消息topic:
        if(pathMatcher.match("kebai/uc/**",topic)){
//            log.info("GW Request:"+payload);
        }

        //网关在线状态topic
        if(pathMatcher.match("kebai/uc/gw/?????????",topic)){
//            log.info("GW Status:"+payload);
        }
    }

}
